//
// Created by leisurexi on 11/29/20.
// file_server.c
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <lib/packet.h>

#define BUF_SIZE 1024

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    int server_sock, client_sock;
    struct packet read_buf, write_buf;
    int recv_len, recv_cnt;
    char content[1024];
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len;

    if (argc != 2) {
        printf("Usage : %s <port>\n", argv[0]);
        exit(0);
    }

    server_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (server_sock == -1)
        error_handling("socket() error");

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(atoi(argv[1]));

    int on = 1;
    setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    if (bind(server_sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1)
        error_handling("bind() error");

    if (listen(server_sock, 5) == -1)
        error_handling("listen() error");

    client_addr_len = sizeof(client_addr);
    while (1) {
        bzero(&read_buf, sizeof(read_buf));
        bzero(&write_buf, sizeof(write_buf));

        recv_len = 0;

        client_sock = accept(server_sock, (struct sockaddr *) &client_addr, &client_addr_len);
        if (client_sock == -1)
            error_handling("accept() error");

        read(client_sock, &read_buf, 4);

        while (recv_len < read_buf.len) {
            recv_cnt = read(client_sock, read_buf.data, read_buf.len);
            recv_len += recv_cnt;
        }

        char filename[read_buf.len];
        strncpy(filename, read_buf.data, strlen(read_buf.data) - 1);
        FILE *fp = fopen(filename, "r");
        if (!fp)
            printf("File not exists: %s", filename);

        struct stat statbuf;
        stat(filename, &statbuf);
        int size = statbuf.st_size;
        write_buf.len = size;

        while (fgets(content, 1024, (FILE *) fp)) {
            strcat(write_buf.data, content);
        }
        fclose(fp);

        write(client_sock, &write_buf, sizeof(write_buf));
        close(client_sock);
    }
// /home/leisurexi/Documents/clion-2020.1.3/Install-Linux-tar.txt
}